{% extends "_base_home.html" %}
{% block main %}
<script src="/static/page/role_right.js"></script>

<nav>
    <button class=" mb-3 btn btn-sm btn-primary float-right" data-toggle="modal"  data-target="#exampleModal">新增权限</button>
</nav>
<table id="permission_table"></table>
<nav >
    <ul id="pagination" class="pagination float-right">

    </ul>
</nav>

<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-xl" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLabel">修改角色信息</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <table id="all_permission_table"></table>
                <nav >
                    <ul id="permission_page" class="pagination mt-3 float-right">

                    </ul>
                </nav>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>
<div class="modal fade" id="roleModal" tabindex="1" role="dialog" aria-labelledby="roleModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="roleModalLabel">新增角色</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form>
                    <div class="form-group">
                        <label for="new_role_name" class="col-form-label">角色名:</label>
                        <input type="text" class="form-control" id="new_role_name">
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="addRole" >提交</button>
            </div>
        </div>
    </div>
</div>
<script>
    let result = {{ result | raw }};
    let permissions = result.records;
    let modifyId = '';
    var permissionModal = {}
    console.log('permission',permissions)
    function format (value, row, index) {
        return `
            <button data-id="${row.id}" onclick="removePermission(${row.id})" class="btn btn-sm btn-danger">删除</button>
          `;
    }
    function formatPermissionTable (value, row, index) {
        return `
            <button data-id="${row.id}" onclick="addPermission(${row.id})" class="btn btn-sm btn-danger">添加</button>
          `;
    }

    function renderPage(){
        const searchParams = new URLSearchParams(window.location.search);
        const roleId = searchParams.get('roleId');
        $("#pagination").append('<li class="page-item">\n' +
            '            <a class="page-link" href="/role_permission?roleId='+roleId+'">首页</a>\n' +
            '        </li>')
        for(let i=0;i<result.totalPages;i++){
            let index = i+1;
            const active = index===result.currentPage?' active':'';
            $("#pagination").append(`<li class="page-item ${active}"><a class="page-link" href="/roles?page=${index}">${index}</a></li>`)
        }
        if(!result.currentPage && (result.currentPage!==result.totalPages)){
            $("#pagination").append(`<li class="page-item">
            <a class="page-link" href="/roles?page=${result.currentPage+1}">下一页</a>
        </li>`)
        }
    }

    function renderPermissionPage(){
        const totalPages = permissionModal.getTotal();
        const current = permissionModal.getCurrent();
        console.log('totalPages',totalPages, current)
        $("#permission_page").append('<li class="page-item">\n' +
            '            <a class="page-link" onclick="goFirst">首页</a>\n' +
            '        </li>')
        for(let i=0;i<totalPages;i++){
            let index = i+1;
            const active = index===current?' active':'';
            $("#permission_page").append(`<li class="page-item ${active}"><a class="page-link" onclick="goPage(${index})">${index}</a></li>`)
        }

        if(!current && (current!==totalPages)){
            $("#permission_page").append(`<li class="page-item">
            <a class="page-link" onclick="goNext">下一页</a>
        </li>`)
        }
    }
    function goFirst(){
        permissionModal.goFirst();
        permissionModal.getData().then((data)=>{
            initPermissionTable("all_permission_table", data.records??[],formatPermissionTable)
        }).catch((msg)=>{
            alert(msg)
        })
    }
    function goPage(page){
        permissionModal.setPage(page);
        permissionModal.getData().then((data)=>{
            initPermissionTable("all_permission_table", data.records??[],formatPermissionTable)
        }).catch((msg)=>{
            alert(msg)
        })
    }
    function goNext(){
        permissionModal.next();
        permissionModal.getData().then((data)=>{
            initPermissionTable("all_permission_table", data.records??[],formatPermissionTable)
        }).catch((msg)=>{
            alert(msg)
        })
    }

    $('#exampleModal').on('show.bs.modal', function (event) {
        var button = $(event.relatedTarget) // Button that triggered the modal
        var rolename = button.data('rolename') // Extract info from data-* attributes
        modifyId = button.data('id')
        permissionModal = getAllPermission();
        permissionModal.getData().then((data)=>{
            initPermissionTable("all_permission_table", data.records??[],formatPermissionTable)
            renderPermissionPage();
        }).catch((msg)=>{
            alert(msg)
        })
    })
    $(document).ready(function(){
        initTable("permission_table", permissions, format)
        renderPage();
        $('#submitBtn').click(function (e) {
            e.preventDefault();
            var data = {
                role_name: $('#role_name').val(),
                id: modifyId
            };
            $.ajax({
                type: 'POST',
                url: '/api/updateRole',
                data: JSON.stringify(data),
                success: function (resp) {
                    if (resp.code === 200) {
                        alert('更新成功');
                        location.reload();
                    } else {
                        alert(resp.info)
                    }
                },
                contentType: 'application/json;charset=UTF-8',
                dataType: 'json'
            });
        });

        $("#addRole").click((e)=>{
            e.preventDefault();
            const roleName = $("#new_role_name").val()
            const data = {
                role_name: roleName
            }
            $.ajax({
                type: 'POST',
                url: '/api/addRole',
                data: JSON.stringify(data),
                success: function (resp) {
                    if (resp.code === 200) {
                        alert('更新成功');
                        location.reload();
                    } else {
                        alert(resp.info)
                    }
                },
                contentType: 'application/json;charset=UTF-8',
                dataType: 'json'
            });
        })
    })
</script>
{% endblock %}
